<?php
namespace Admin\Controller;
use Think\Controller;
use Common\Controller\_AllController;
use Common\ORG\Page,Common\ORG\AttUpload,Common\ORG\Excel;
/**
 * 后台任务运行
 *
 */
class CronController extends _AllController {
    const WEIGUI_DAYS = 30; //超过30天违规
    const WEIGUI_MAX_DAYS = 100;//违规朝时，最大100天，之后就不更新了   
    const SEND_TYPE = 20;  //定时发送
    const UNSEND_STATUS = 30;  //发送状态-待发送
    const FAILESEND_STATUS = 0;  //发送状态-发送失败
    //初始化函数
    public function _initialize()
	{
		parent::_initialize();
        if ('cli'!=php_sapi_name()) {
            exit("请在CLI环境下执行定时任务");
        }
    }

    public function index()
    {
        // index actioon
    }

    //合同违规天数更新，更新合同违规天数
    public function contractWeigui()
    {
        $MContract = D('Admin/Contract');
        $where = array();
        $where['c.sign_status'] = array('neq',   \Admin\Model\ContractModel::SIGN_OK);
        //更新待审核的合同、以及签订中的合同
        $where['c.state'] = array('in',  array(  \Admin\Model\ContractModel::STATE_NEED_AUTH, \Admin\Model\ContractModel::STATE_SIGNING  ));
        //签订天数超过100天就不更新
        $whereday = array();
        $whereday['_logic'] = 'OR';
        $whereday['c.sign_day'] =  array('lt', self::WEIGUI_MAX_DAYS);
        $whereday['_string'] = ' ISNULL(c.sign_day)';
        $where['_complex'] = $whereday;
        $cnt = $MContract->alias("c")->where( $where )->count();
        $pageSize = 1000;//每次处理一条记录
        $pall = $cnt ? ceil($cnt/$pageSize) : 0;   
        echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  解析合同签订天数开始 ', str_repeat('*', 6),"\n";
        echo "更新",str_repeat(' ', 3),$cnt,str_repeat(' ', 3),"条数据\n";    
        for($p=0; $p<$pall; $p++){
            $start = $pageSize*$p;
            $list = $MContract->alias('c')
                              ->field("c.order_num,c.contract_id,c.sign_status,c.state,c.sign_day,c.start_time")
                              ->where( $where )
                              ->order("c.start_time desc")
                              ->limit($start.','.$pageSize)
                              ->select();
            foreach ($list as $v) {
                $ret = $this->_getLastPay2Now( $v['contract_id']);
                if (FALSE !== $ret && $ret) {
                    $wherec = array();
                    $dup = array();
                    $wherec['contract_id'] = array('eq', $v['contract_id']);
                    $where['weigui_status'] = array('eq', \Admin\Model\ContractModel::WEIGUI_STATUS_UNKNOWN);
                    $dup['sign_day'] = $ret;
                    if ( $ret > self::WEIGUI_DAYS) {
                        $dup['weigui_status'] = \Admin\Model\ContractModel::WEIGUI_STATUS_NEDD_EXPORT;
                    }
                    $MContract->where( $wherec )->save( $dup );
                }
                else {
                    echo " ERROR 合同：", $v['order_num'],'   获取天数失败',"\n";
                }
            }
        }
        echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  解析合同签订天数结束 ', str_repeat('*', 6),"\n\n";
    }

    private function _getLastPay2Now( $contract_id )
    {
        $MPay = D('Admin/Pays');
        $wherep = array();
        $wherep['p.record_status'] = array('eq', \Admin\Model\PaysModel::RECORD_STATUS_VALID);
        $wherep['p.audit_res'] = array('eq', \Admin\Model\PaysModel::AUDIT_OK);
        $wherep['p.contract_id'] = array('eq', $contract_id);
        $data = $MPay->alias("p")->field("p.pay_time")->where( $wherep )->order('pay_time desc')->find();
        if ($data&&$data['pay_time']) {
            $pay_time = $data['pay_time'];
            $tm = time() - strtotime( $pay_time);
            $days = $tm ? floor( $tm/(60*60*24) ):0;
            return $days;
        }
        else {
            return FALSE;
        }
    }

    /**
     * 定时任务：从电子合同系统更新最新签订的合同
     * 
     * 
    */
    public function econtract()
    {
        $MService = D('Admin/Econtract', 'Service');
        $data = $MService->batchRead();
        echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  电子合同更新签订状态开始 ', str_repeat('*', 6),"\n";
        //根据接口返回的数据更新合同状态
        if ($data['rcode']) {
            $MContract = D('Admin/Contract');
            $MSurvey = D('Admin/CustomerSurvey');
            $where = $wherecs = array();
            $dup = $dCSurvey = array();
            $dup['sign_status'] = \Admin\Model\ContractModel::SIGN_OK;
            $dup['state'] = \Admin\Model\ContractModel::STATE_SERVICE;
            $where['state'] = array('eq', \Admin\Model\ContractModel::STATE_SIGNING); //更新签订中的合同
            foreach ($data['data'] as $vd ) {
                $dup['backcontract'] = $vd['viewpdf_url']; //更新备注地址
                $where['order_num'] = array('eq', $vd['contract_id']);
                //同步客户信息到合同
                if (isset($vd['customer_name']) && isset($vd['customer_phone']) ){
                    $dup['second_party_name'] = $vd['customer_name'];
                    $dup['second_party_phone'] = $vd['customer_phone'];
                }
                $ret = $MContract->where( $where )->save( $dup );
                 //更新对应客户问卷数据
                 if (isset($vd['survey']) && $vd['survey'] ){
                     $ds = $vd['survey'];
                     $wherecs['survey_code'] = array('eq', $ds['survey_code'] );
                     $find = $MSurvey->where( $wherecs )->find();
                     $where_c = array();
                     $where_c['order_num'] = $where['order_num'];
                     $dcontract = $MContract->where( $where_c )->find();
                     if (!$find &&$dcontract){
                         $dCSurvey['survey_code'] = $ds['survey_code'];
                         $dCSurvey['survey_template_id'] = $ds['survey_template_id'];
                         $dCSurvey['version'] = $ds['version'];
                         $dCSurvey['rank'] = $ds['survey_score'];
                         $dCSurvey['rank_title'] = $ds['rank_title'];
                         $dCSurvey['create_time'] = $ds['create_time'];
                         $dCSurvey['rank_level'] = $ds['rank_char'];
                         $dCSurvey['customer_id'] = $dcontract['customer_id'];
                         $aid = $MSurvey->data( $dCSurvey )->add();
                     }
                 }
                echo " OK 更新成功，合同编号：", $vd['order_num'],'   更新电子合同成功 , 合同预览地址:',$vd['viewpdf_url'],"\n";
            }
        }
        else {
            // 接口获取数据失败
            echo "Error 获取接口数据失败　　\n";    
        }

        echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  电子合同更新签订状态结束 ', str_repeat('*', 6),"\n\n";
    }

    /**
     * 定时任务：更新订阅用户
     * 
     * 更新最近的 20 条记录,只更新7天之内的客户
     * 
    */
    public function syncSubscriber()
    {
        $MSubscriber = D('Admin/QySubscriber');
        $wheres = array();
        $wheres['qy_subscriber_sync'] = array('in', array ( SubscriberService::SYNC_NEED_CREATE,
                                                            SubscriberService::SYNC_NEED_UPDATE
                                                            ) 
                                             );
        $before7days = strtotime("-7 days");
        $wheres['create_time'] = array('gt', date('Y-m-d H:i:s', $before7days) );
        $wheres['end_time'] =  array('gt', date('Y-m-d 23:59:59') );
        $arrQy = array();        
        echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  订阅用户同步开始 ', str_repeat('*', 6),"\n";
        $data = $MSubscriber->where( $wheres )->limit('20')->order('create_time ASC')->select();
        if ($data){
            foreach ($data as $vd) {
                $dataUp = $whereu = array();
                if (!isset($arrQy[$vd['qy_code']]) )
                    $arrQy[$vd['qy_code']] = new \Common\ORG\Qy($vd['qy_code'] );
                    $departyMent =  explode(',', $vd['qy_subscriber_department']);
                    //创建新的用户与同步信息调用不同的接口
                    if ($vd['qy_subscriber_sync'] == SubscriberService::SYNC_NEED_CREATE ){ 
                        $retData = $arrQy[$vd['qy_code']]->createUser($vd['qy_subscriber_userid'], $vd['qy_subscriber_name'], $departyMent,
                                                    $vd['qy_subscriber_mobile'], $vd['qy_subscriber_position'], $vd['qy_subscriber_gender'],
                                                    $vd['qy_subscriber_email'], $vd['qy_subscriber_enable']);
                        $dataUp['qy_subscriber_sync'] = $retData['rcode'] ? SubscriberService::SYNC_DOWN: SubscriberService::SYNC_ERROR_CREATE;
                        if ($retData['rcode']) //如果订阅用户创建成功，更新用户状态为服务中
                            $dataUp['qy_subscriber_status'] = SubscriberService::STATUS_IN_SERVICE;
                    }
                    else{ //更新用户
                        $retData = $arrQy[$vd['qy_code']]->updateUser($vd['qy_subscriber_userid'], $vd['qy_subscriber_name'], $departyMent,
                                                    $vd['qy_subscriber_mobile'], $vd['qy_subscriber_position'], $vd['qy_subscriber_gender'],
                                                    $vd['qy_subscriber_email'], $vd['qy_subscriber_enable']);
                        $dataUp['qy_subscriber_sync'] = $retData['rcode'] ? SubscriberService::SYNC_DOWN: SubscriberService::SYNC_ERROR_UPDATE;
                    }
                    
                    $dataUp['sync_message'] = $retData['msg'];
                    $whereu['qy_subscriber_id'] = array('eq', $vd['qy_subscriber_id']);
                    $MSubscriber->where( $whereu )->save( $dataUp );
            }
        }
        else{
            echo "NOTICE 没有要更新的数据　　\n"; 
        }

        echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  订阅用户同步结束 ', str_repeat('*', 6),"\n\n";
    }


    /**
     * 企业号订阅用户计算有效期
     * 
     * 在客户有效期到达时间之后，自动更新订阅订阅状态以及同步信息
     * 
    */
    public function timeSubscriber()
    {
        //
    }

    /**
     * 定时任务：企业号中发送定时消息
     * 
     * 
    */
    public function sendMessages(){
        $MSubscriber = D('Admin/QyMessage');
        $wheres = array();
        //查询现在之前2分钟之内，没有发送或发送失败的数据
        $wheres['send_time'] = array('between', [date("Y-m-d H:i:s",strtotime(date('Y-m-d H:i:s'))-120),date('Y-m-d H:i:s')]);
        $wheres['send_type'] = array('eq', self::SEND_TYPE);
        $wheres['status'] = array('in', [self::UNSEND_STATUS,self::FAILESEND_STATUS]);
        $sendList = $MSubscriber->where($wheres)->select();
        if($sendList){
            foreach ($sendList as $mk => $mval) {
                $dataUp = $whereu = array();
                $MQy[$mk] =  new \Common\ORG\Qy($mval['qy_code']);
                if( $mval['message_type'] == 'mpnews' ){
                    $returnDate[$mk] = $MQy[$mk]->uploadmpnewsMessage($mval['touser'],$mval['toparty'],$mval['totag'],$mval['message_type'],
                        $mval['agentid'],unserialize($mval['message_content']));
                }
                else if( $mval['message_type'] == 'text' ){
                    $returnDate[$mk] = $MQy[$mk]->uploadtextMessage($mval['touser'],$mval['toparty'],$mval['totag'],$mval['message_type'],
                        $mval['agentid'],unserialize($mval['message_content']));
                }else if( $mval['message_type'] == 'file' ){
                    $returnDate[$mk] = $MQy[$mk]->uploadfilemsgMessage($mval['touser'],$mval['toparty'],$mval['totag'],$mval['message_type'],
                        $mval['agentid'],unserialize($mval['message_content']));
                }
                $whereu['message_id'] = array('eq', $mval['message_id']);
                //根据发送结果，更新数据发送状态、打印提示消息
                if($returnDate[$mk]['rcode']){
                    $dataUp['status'] = 10;
                    $MSubscriber->where( $whereu )->save( $dataUp );
                    echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  已向企业号'.$mval['qy_code'].'发送'.$mval['message_type'].'类型消息 ', str_repeat('*', 6),"\n";
                }else{
                    $dataUp['status'] = 0;
                    $MSubscriber->where( $whereu )->save( $dataUp );
                    echo str_repeat('*', 6)  , date('Y-m-d H:i:s'), '  已向企业号'.$mval['qy_code'].'发送消息失败-'.$returnDate[$mk]['msg'], str_repeat('*', 6),"\n";
                }
            }
        }
    }


}
